package com.example.rabbit.demo.confirm;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @program: rabbit-demo
 * @description:
 * @author: zhaoliang
 * @create: 2019-12-30 13:38
 */
public class ProducerConfirm {

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.200.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/zl");
        connectionFactory.setPassword("123456");
        connectionFactory.setUsername("zhaoliang");

        //2.通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //3.通过connection创建一个channel
        Channel channel = connection.createChannel();

        //4.指定消息投递模式：消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_confirm_exchange";
        String routingKey1 = "confirm.save";
        String routingKey2 = "confirm.update";
        String routingKey3 = "confirm.find";
        //5.发送一条消息
        String msg1 = "Hello RabbitMQ Send confirm message"+routingKey1;
        String msg2 = "Hello RabbitMQ Send confirm message"+routingKey2;
        String msg3 = "Hello RabbitMQ Send confirm message"+routingKey3;
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2)//1非持久化，2代表持久化
                .contentEncoding("UTF-8")
                .expiration("10000")//过期时间
                .build();
        channel.basicPublish(exchangeName,routingKey1,null,msg1.getBytes());
        channel.basicPublish(exchangeName,routingKey2,null,msg2.getBytes());
        channel.basicPublish(exchangeName,routingKey3,properties,msg3.getBytes());

        //6.添加一个确认监听
        channel.addConfirmListener(new ConfirmListener() {
            //成功
            @Override
            public void handleAck(long l, boolean b) throws IOException {
                System.out.println("===ack!===============");
            }
            //失败
            @Override
            public void handleNack(long l, boolean b) throws IOException {
                System.out.println("====no ack!==============");
            }
        });
       /* channel.close();
        connection.close();*/

    }
}
